const userModel = require("../model/user")
module.exports={
    async register(ctx){
        //1. 获取用户名 & 密码
        let {name,password} = ctx.request.body
        //2. 对用户名和密码进行一次格式检验
        ctx.verifyParams({
            name: {
                type:'string',
                required:true
            },
            password:{
                type:'string',
                required:true
            }
        })
        //3.判断当前用户是否已经存在 如果存在则报409代表冲突
        const users = await userModel.find({name});
        if(users.length>=1){
            ctx.throw(409,"当前用户已经存在");
            console.log("----")
        }
        //4.对密码进行加密
        const bcrypt = require('bcryptjs');
        const saltRounds = 10;
        const salt = bcrypt.genSaltSync(saltRounds);
        password = bcrypt.hashSync(password, salt);
        //5.入库!
        const user = await userModel.create({name,password});
        ctx.body=user;
    }
}
